package org.roger.index.filter;

import java.io.IOException;

import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.payloads.PayloadHelper;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.PayloadAttribute;
import org.apache.lucene.util.BytesRef;

/**
 * 对项加入有效负载
 * @author luoweiyi
 */
public class PayloadsFilter extends TokenFilter{
	
	private CharTermAttribute termAtt;
	private PayloadAttribute payloadAttr;
	private BytesRef bytesRef;

	public PayloadsFilter(TokenStream input,float boost) {
		super(input);
		termAtt = addAttribute(CharTermAttribute.class);
		payloadAttr = addAttribute(PayloadAttribute.class);
		bytesRef = new BytesRef(PayloadHelper.encodeFloat(boost));
	}

	@Override
	public boolean incrementToken() throws IOException {
		if(input.incrementToken()){
			String term = termAtt.toString();
			if(term.contains("freshness")){
				payloadAttr.setPayload(bytesRef);
			}else{
				payloadAttr.setPayload(null);
			}
			return true;
		}else{
			return false;
		}
	}
}
